"""
https://docs.pytest.org/en/latest/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session
"""
import pytest
from common.appium_manage import start_appium,stop_appium
from appium import webdriver
from appium.webdriver.webdriver import WebDriver
import os

@pytest.fixture(scope="session",autouse=True)
def sessionmanage():
    start_appium()
    print("session begin..")
    yield
    stop_appium()
    print('session end...')

@pytest.fixture(scope='module',autouse=True)
def driver():
    # chromedriver版本要跟自己手机上的版本匹配
    chromedriver = os.path.join(os.path.dirname(__file__),'chromedriver/chromedriver.exe')
    desired_caps = {
        'platformName': 'Android',  # 平台
        'platformVersion': '7.1.2',  # Android 版本，
        'automationName': "UiAutomator2",
        'noReset': True,  # 不要重置手机状态
        'fullReset': False,
        "appPackage":"org.cnodejs.android.md", # 启动app的包名
        "appActivity":".ui.activity.LaunchActivity", # 启动页名
        "chromedriverExecutable": chromedriver, # chromedriver的配置
        # "autoWebview":True, # 设置自动切换webview
    }
    driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_caps)
    driver.implicitly_wait(5)
    import time
    time.sleep(6)
    print('创建driver.....')
    yield driver  # 传递driver
    driver.quit()
    print('关闭driver.....')


@pytest.fixture(scope='function',autouse=True)
def save_screenshot(driver:WebDriver):
    yield
    """
    每次截图都放到screenshots 目录下
    screenshots 每天创建一个目录，再在每天的目录下创建截图文件
    """
    import os,time
    screenshots_dir = os.path.join(os.path.dirname(__file__),'screenshots')
    if not os.path.exists(screenshots_dir):
        os.mkdir(screenshots_dir)
    day_dir = os.path.join(screenshots_dir,time.strftime("%Y_%m_%d"))
    if not os.path.exists(day_dir):
        os.mkdir(day_dir)
    pngfile = os.path.join(day_dir,time.strftime('%H_%M_%S')+'.png')
    driver.save_screenshot(pngfile)
    from allure_commons.types import AttachmentType
    import allure
    # allure.attach(driver.get_screenshot_as_png(),name='screenshot')
    allure.attach(driver.get_screenshot_as_png(), name='Screenshot', attachment_type=AttachmentType.PNG)